package controller;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import po.User;
import serivce.personService;
import serivce.userService;

@Controller
public class PersonController {
	
	@Autowired
	private personService ps;
	
	@Autowired
	private userService us;
	
	
	@RequestMapping(value="/index")
	public String index() {
		return "/html/index.html";
	}
	
	/*
	 * 判断登录
	 * */
	@RequestMapping(value="/login",method = RequestMethod.POST)
	@ResponseBody
	public String  login(User user,HttpServletRequest request,HttpServletResponse response) {
		HttpSession session = request.getSession();
		System.out.println(user);
		User u = us.queryByAccount(user.getAccount());
		System.out.println(u);
		if(u!=null) {
			if(u.getPassword().equals(u.getPassword())) {
				session.setAttribute("user", user);
				return "success";
			}else {
				return "error";
			}
		}else {
			return "error";
		}
	}
	
	@RequestMapping(value="/fileupload",method = RequestMethod.POST)
	@ResponseBody
	public String aaaaa(@RequestParam("username") String username,@RequestParam("picture") List<MultipartFile> picture,HttpServletRequest request) {
		//获得文件上传的路径
		String uploadpath = request.getSession().getServletContext().getRealPath("/upload/");
		
		String expandname = null;
		
		if(picture!=null && picture.size()!= 0) {
			for(MultipartFile file:picture) {
				//随机生成一个文件名
				UUID uuid = UUID.randomUUID();
				String filename = file.getOriginalFilename();
				//获取文件拓展名
				expandname = filename.substring(filename.lastIndexOf('.'));
				//创建上传文件对象
				File f = new File(uploadpath+uuid+expandname);
				try {
					//上传
					file.transferTo(f);
				} catch (IllegalStateException e) {
					System.out.println("走到这");
					e.printStackTrace();
					return "error";
				} catch (IOException e) {
					e.printStackTrace();
					return "error";
				}
			}
			return "success";
		}
		return username;
	}
	
	
}
